package codetop.microsoft.T114;

import util.TreeNode;

/**
 * @Author: 18362
 * @Create: 2022-08-16 23:08:06 星期二
 */
class Solution {
    public void flatten(TreeNode root) {
        flattenTree(root);
    }

    private TreeNode flattenTree(TreeNode root) {
        if (root == null)
            return null;
        TreeNode left = flattenTree(root.left), right = flattenTree(root.right);
        if (left == null && right == null)
            return root;
        else if (left == null && right != null) {
            return right;
        } else if (left != null && right == null) {
            root.right = root.left;
            root.left = null;
            return left;
        } else {
            left.right = root.right;
            root.right = root.left;
            root.left = null;
            return right;
        }
    }
}